﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using Medianamik.Core;
using System.Globalization;
using System.Web.UI;
using System.Collections.Specialized;
using System.Collections.ObjectModel;
using Medianamik.Globalization;

namespace Medianamik.UI.Controls
{
    [ToolboxData("<{0}:TranslatorBox runat=server></{0}:TranslatorBox>")]
    public class TranslatorBox : CompositeControl
    {
        public const string LANGUAGE_ATTRIBUTE_NAME = "lang";

        private List<CultureInfo> cultures { get { return ConfigManager.GetMedianamikCultures().Select(c => c.CultureInfo).ToList(); } }

        protected override void CreateChildControls()
        {
            Controls.Clear();
            CreateControlHierarchy();
            ClearChildViewState();
        }

        protected virtual void CreateControlHierarchy()
        {
            foreach (CultureInfo culture in cultures)
            {
                TextBox textbox = new TextBox();
                textbox.ID = "text" + culture.Name.Replace("-", "").ToUpper();
                textbox.CssClass = "TxtBox";
                textbox.Attributes.Add(LANGUAGE_ATTRIBUTE_NAME, culture.Name);
                if (TextBoxWidth.HasValue)
                {
                    textbox.Width = TextBoxWidth.Value;
                }
                if (TextBoxHeight.HasValue)
                {
                    textbox.TextMode = TextBoxMode.MultiLine;
                    textbox.Height = TextBoxHeight.Value;
                }


                if (_values != null && _values.ContainsKey(culture.Name))
                {
                    textbox.Text = _values[culture.Name];
                }

                Controls.Add(textbox);

                if (Required)
                {
                    RequiredFieldValidator reqValidator = new RequiredFieldValidator();
                    reqValidator.ID = "required" + culture.Name.Replace("-", "").ToUpper();
                    reqValidator.ControlToValidate = textbox.ID;

                    //Par défaut, nous ne voullions pas afficher le contrôle. Alors, si non setté, on veut caché le control
                    if (ErrorMessageHidden.GetValueOrDefault(true))
                        reqValidator.Display = ValidatorDisplay.None;
                    else
                        reqValidator.Display = ValidatorDisplay.Dynamic;

                    reqValidator.ErrorMessage = ErrorMessage + " " + Translator.Translate("medianamik_cultures", culture.Name);
                    reqValidator.EnableClientScript = false;
                    Controls.Add(reqValidator);
                }
            }
        }

        public bool Required
        {
            get
            {
                object o = ViewState["Required"];
                if (o == null)
                    return default(bool);
                return (bool)o;
            }
            set { ViewState["Required"] = value; }
        }

        public string Label
        {
            get
            {
                object o = ViewState["Label"];
                if (o == null)
                    return String.Empty;
                return (string)o;
            }
            set { ViewState["Label"] = value; }
        }

        public string ErrorMessage
        {
            get
            {
                object o = ViewState["ErrorMessage"];
                if (o == null)
                    return String.Empty;
                return (string)o;
            }
            set { ViewState["ErrorMessage"] = value; }
        }

        public int? TextBoxWidth
        {
            get
            {
                return (int?)ViewState["TextBoxWidth"];
            }
            set
            {
                ViewState["TextBoxWidth"] = value;
            }
        }
        public int? TextBoxHeight
        {
            get
            {
                return (int?)ViewState["TextBoxHeight"];
            }
            set
            {
                ViewState["TextBoxHeight"] = value;
            }
        }

        public bool? ErrorMessageHidden
        {
            get
            {
                return (bool?)ViewState["ErrorMessageHidden"];
            }
            set
            {
                ViewState["ErrorMessageHidden"] = value;
            }
        }

        public override void RenderControl(HtmlTextWriter writer)
        {
            writer.RenderBeginTag(HtmlTextWriterTag.Table);
            foreach (Control control in Controls)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                switch (control.GetType().Name)
                {
                    case "TextBox":
                        var textbox = control as TextBox;
                        string lang = textbox.Attributes[LANGUAGE_ATTRIBUTE_NAME];
                        if (!String.IsNullOrEmpty(lang))
                        {
                            #region Label

                            writer.RenderBeginTag(HtmlTextWriterTag.Td);

                            writer.AddAttribute(HtmlTextWriterAttribute.Class, "EditionPage");
                            writer.AddAttribute(HtmlTextWriterAttribute.For, textbox.ClientID);
                            writer.RenderBeginTag(HtmlTextWriterTag.Label);
                            writer.Write(Label);
                            writer.Write(Translator.Translate("medianamik_cultures", lang) + " :");

                            writer.RenderEndTag();

                            #endregion

                            #region TexBox

                            writer.RenderBeginTag(HtmlTextWriterTag.Td);

                            textbox.RenderControl(writer);
                            if (Required)
                            {
                                writer.Write("&nbsp;<span class=\"ChampObligatoire\">*</span>&nbsp;");
                            }

                            writer.RenderEndTag();

                            #endregion

                            writer.RenderEndTag();

                        }
                        break;
                    default:
                        control.RenderControl(writer);
                        break;
                }
                writer.RenderEndTag();
            }
            writer.RenderEndTag();
        }

        private void SetTextBoxValues(IEnumerable<TextBox> pTextBoxes, IDictionary<String, String> pValues)
        {
            foreach (TextBox txt in pTextBoxes)
            {
                string key = pValues.Keys.FirstOrDefault(k => k.Equals(txt.Attributes[LANGUAGE_ATTRIBUTE_NAME], StringComparison.InvariantCultureIgnoreCase));
                if (key != null)
                {
                    txt.Text = pValues[key];
                }

            }
        }

        private IDictionary<String, String> _values;
        public IDictionary<String, String> Values
        {
            get
            {
                if (_values == null)
                {
                    _values = new Dictionary<String, String>();
                    EnsureChildControls();
                    foreach (TextBox textbox in Controls.OfType<TextBox>())
                    {
                        _values.Add(textbox.Attributes[LANGUAGE_ATTRIBUTE_NAME], textbox.Text);
                    }
                }
                return _values;
            }
            set
            {
                _values = value;
                SetTextBoxValues(Controls.OfType<TextBox>(), value);
            }
        }
    }
}
